import http from './request'
import { Message } from 'element-ui'
import JSEncrypt from 'jsencrypt'
let base = require('js-base64').Base64

export default {
  //加密方法
  // getRsaCode(str) {
  //     let pubKey = `MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqxuum7dWvUsecJbhX+tMSMXGsd/jE5rdiY2xz46meYFLiatIimLJIeIK2FozpGmwasvMexjhKH2ju3NK/Lzs3BDsulNVLFMNyteYzwac3hF9aQ8o58Kz6bqSSZEs/l20/8m8Uc0ARjRvVt8uH+dUsZBCWfizPPs0BxQ4MnudIFvbgoPA9Q3F1mJ0xHB8N0tPnolSpD3V3Fgv808BomjW6dCLr6Pdkj2pBZWVpCRuKjYklYiAwtXq1DUd5Q6oa7MdBODbn7/8bmDyxm1lma1uYZ8Ub/M1kN5oEZ4A+YXVWJvn949XCUMcXLHOUYdMzegtL4w8Ll9aRmXe2mrPzlxdhQIDAQAB`;// ES6 模板字符串 引用 rsa 公钥
  //     let encryptStr = new JSEncrypt();
  //     encryptStr.setPublicKey(pubKey); // 设置 加密公钥
  //     let data = encryptStr.encrypt(str.toString());  // 进行加密
  //     return data;
  // },
  // 去除首尾空格
  removeSpace(data) {
    for (const key in data) {
      const value = data[key]
      if (typeof value === 'string') {
        data[key] = value.trim()
      }
    }
    return data
  },
  flat(arr, menulist) {
    menulist.forEach(item => {
      if (Array.isArray(item.highestRoleMenuVos)) {
        if (item.highestRoleMenuVos.length > 0) {
          flat(arr, item.highestRoleMenuVos)
        } else {
          arr.push(item)
        }
      } else {
        arr.push(item)
      }
    })
    return arr
  },
  //   加密
  getBase64Code(str) {
    let data = base.encode(str)
    return data
  },
  //保存cookie 入参 保存的名称 ,值 , 保存时间（天）
  setCookie(c_name, value, expiredays) {
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie = c_name + '=' + escape(value) + (expiredays == null ? '' : ';expires=' + exdate.toGMTString())
  },
  //获取cookie
  getCookie(userName) {
    if (document.cookie.length > 0) {
      var c_start
      var c_end
      c_start = document.cookie.indexOf(userName + '=')

      if (c_start != -1) {
        c_start = c_start + userName.length + 1
        c_end = document.cookie.indexOf(';', c_start)
        if (c_end == -1) {
          c_end = document.cookie.length
        }
        return unescape(document.cookie.substring(c_start, c_end))
      }
    }
    return ''
  },
  //公共正则验证方法
  fieldTest(type, str) {
    let regular = ''
    if (type == 'phone') {
      regular = /^[1][3,4,5,7,8,9][0-9]{9}$/
    } else if (type == 'money') {
      regular = /^[0]*\d{1,6}(\.\d{0,2})?$/
    } else if (type == 'decimal') {
      regular = /^([0-9]\d{0,7}|0)(\.\d{1,4})?$/
    } else if (type == 'count') {
      regular = /(^[0]*\d{1,6}$)/
    }
    return regular.test(str)
  },
  // 获取省市区方法 type { province:省 city:市 area:区 }  id 获取市区所需id 省不用传
  async getAddressList(type, id) {
    return await new Promise((resolve, reject) => {
      let url = ''
      if (type == 'province') {
        url = '/address/listAllProvince'
      } else if (type == 'city') {
        url = '/address/listAllCityByProvinceId/?provinceId=' + id
      } else if (type == 'area') {
        url = '/address/listAllAreasByCityId/?cityId=' + id
      }
      http({
        method: 'post',
        url: url
      })
        .then(res => {
          if (res.code === 0) {
            resolve(res.data)
          } else {
            Message.error(res.msg)
          }
        })
        .catch(err => {
          reject(err)
          console.log(err)
        })
    })
  },
  //获取下拉数据
  async getSelectList(dictType) {
    return await new Promise((resolve, reject) => {
      http({
        method: 'post',
        url: '/dictionary/selectDictionaryList.json',
        data: {
          dictType: dictType
        }
      })
        .then(res => {
          if (res.success) {
            resolve(res.data)
          } else {
            Message.error(res.message)
          }
        })
        .catch(err => {
          reject(err)
          console.log(err)
        })
    })
  },
  //组成树形结构方法 treeData 需转换的数组  parentId 父节点id  parentIdKeyName 父节点id字段名称
  // idKeyName 自身id字段名称 labelKeyName自身内向字段名称  params 需额外加入的字段可多个 必须为json对象 且key value与转换后一致 如:{ isHave:true }
  getTree(treeData, parentId, parentIdKeyName, idKeyName, labelKeyName, params) {
    let treeArr = []
    for (let i = 0; i < treeData.length; i++) {
      let node = treeData[i]
      if (node[parentIdKeyName] == parentId) {
        var arr = this.getTree(treeData, node[idKeyName], parentIdKeyName, idKeyName, labelKeyName, params)
        let newNode = {
          value: node[idKeyName],
          label: node[labelKeyName]
        }
        if (arr.length != 0) {
          newNode['children'] = arr
        }
        for (let key in params) {
          newNode[key] = params[key]
        }
        treeArr.push(newNode)
      }
    }
    return treeArr
  },
  downloadFile(res, filename) {
    var a = document.createElement('a')
    // var blob = new Blob([res], {
    //   type: filename.split('.')[1]
    // })
    // this.dataURLtoBlob
    var blob = this.dataURLtoBlob(res, filename)
    var url = window.URL.createObjectURL(blob)
    a.href = url
    a.download = filename
    a.click()
    window.URL.revokeObjectURL(url)
  },

  dataURLtoBlob(base64Str, filename) {
    var bstr = atob(base64Str),
      n = bstr.length,
      u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    // 下载的是excel格式的文件
    return new Blob([u8arr], { type: filename.split('.')[1] })
  },
  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest()
      // 避免 200 from disk cache
      url = url + `?r=${Math.random()}`
      xhr.open('GET', url, true)
      xhr.responseType = 'blob'
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response)
        }
      }
      xhr.send()
    })
  },
  saveAs(blob, filename) {
    if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveBlob(blob, filename)
    } else {
      const anchor = document.createElement('a')
      const body = document.querySelector('body')
      anchor.href = window.URL.createObjectURL(blob)
      anchor.download = filename

      anchor.style.display = 'none'
      body.appendChild(anchor)

      anchor.click()
      body.removeChild(anchor)

      window.URL.revokeObjectURL(anchor.href)
    }
  }
}
